package com.javademo.multithreadingtest;

import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class ReentrantLockTest {
    public static void main(String[] args) {
        TaskQueue1 taskQueue1 = new TaskQueue1();
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                   log.error("error: {}", e.getMessage());
                }
                try {
                    taskQueue1.addTask("task" + i);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread thread2 = new Thread(() -> {
            while (true){
                String task = null;
                try {
                    task = taskQueue1.getTask();
                    log.info("get task: {}", task);
                } catch (InterruptedException e) {
                    log.error("error: {}", e.getMessage());
                }
            }
        });
        thread1.start();
        thread2.start();
    }
}

@Slf4j
class TaskQueue1 {
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    private Queue<String> queue = new LinkedList<>();

    public void addTask(String s) throws InterruptedException {
        if (lock.tryLock(1, TimeUnit.SECONDS)){
            try {
                queue.add(s);
                condition.signalAll();
            }finally {
                lock.unlock();
            }
        }
    }
    public String getTask() throws InterruptedException {
        if (lock.tryLock(1, TimeUnit.SECONDS)){
            try {
                while (queue.isEmpty()){
                    condition.await();
                }
                return queue.poll();
            }finally {
                lock.unlock();
            }
        }
        return null;
    }
}